#include <stdio.h>
#include <stdlib.h>
#include "../include/queue.h"


struct node {
	queueElementT data;
	struct node *next;
};

struct queueCDT {
	int qty;
	struct node *head, *tail;	
};


static void Error(const char* cartel) {
        fprintf(stderr, cartel);
        exit(EXIT_FAILURE);
}

queueADT 
NewQueue(void) {
	return (queueADT) calloc(sizeof(struct queueCDT), 1);
}
	
void 
FreeQueue(queueADT q) {
	if( q != NULL )  
	{
		
		while(!QueueIsEmpty(q)) {
			Dequeue(q);
		}
		free(q);
	}
}

void
Enqueue(queueADT q, queueElementT elem) {
	struct node *node;

	if((node = calloc(sizeof(struct node), 1)) == NULL)
    Error("No hay mas memoria\n");

	node->data = elem;

	if(q->head == NULL) 
		/* Primer elemento */
		q->head = node;
	else
		q->tail->next = node;

	q->tail = node;
	q->qty++;
}

queueElementT
Dequeue(queueADT q) {
	struct node *node;
  queueElementT elem = NULL;

	if(!QueueIsEmpty(q)) {
          elem = q->head->data;
          node = q->head;
          /* Avanzo la cabeza de la lista */
          q->head = q->head->next;
          if(q->head == NULL)
            q->tail = NULL;
          q->qty--;

          free(node);
  }

	return elem;
}

int 
QueueLength(queueADT q) {

	return q->qty;
}

int 
QueueIsEmpty(queueADT q) {

	return q->qty == 0;
}

